import { Injectable } from '@nestjs/common';
import { CreateMenuDto } from './dto/create-menu.dto';
import { UpdateMenuDto } from './dto/update-menu.dto';
import { Repository, TreeRepository } from 'typeorm';
import { Menu } from './entities/menu.entity';
import { InjectRepository } from '@nestjs/typeorm';

@Injectable()
export class MenusService {
  constructor(
    @InjectRepository(Menu) private menuRepository: Repository<Menu>,
  ) {}
  async create(createMenuDto: CreateMenuDto) {
    const menu = await this.menuRepository.findOneBy({
      menuNo: createMenuDto.menuNo,
    });
    if (menu) {
      return {
        code: 1,
        message: '该系统编码已存在，请重新设置',
      };
    } else {
      const menuSave = createMenuDto;
      if (!menuSave.parentId) {
        menuSave.parentId = 'root';
      }
      await this.menuRepository.save(menuSave);
      return {
        code: 0,
        message: '保存成功！',
      };
    }
  }
  async findAll() {
    const datalist = await this.menuRepository.find();
    return this.getTrees(datalist, 'root');
  }

  getTrees(dataList, parentId) {
    return dataList.reduce((pre, cur) => {
      if (cur.parentId === parentId) {
        cur.children = this.getTrees(dataList, cur['id']);
        return pre.concat(cur);
      }
      return pre;
    }, []);
  }

  async findOne(id: string) {
    const parentMenu: ParentMenu = await this.menuRepository.findOneBy({ id });
    const list = await this.menuRepository.find();
    parentMenu.children = this.getTrees(list, id);
    return parentMenu;
  }

  update(id: string, updateMenuDto: UpdateMenuDto) {
    return this.menuRepository.update(id, updateMenuDto);
  }

  remove(id: string) {
    return this.menuRepository.delete(id);
  }
}
